import { login, logout, getInfo } from "@/api/login"
import { saveAccountAPI, smsLoginAPI } from "@/api/system/user.js"
import { getToken, setToken, removeToken } from "@/utils/auth"
import defAva from "@/assets/images/profile.jpg"
import { GetNoMessageAPI } from "@/api/index.js"

const useUserStore = defineStore("user", {
  state: () => ({
    workbenchDataType: "", // 工作台识别 1管理员 2员工
    socket: 0,
    msgTotal: 0,
    msgIsShow: false,
    accountsId: "", // 账套id
    token: getToken(),
    username: "",
    nickName: "",
    avatar: "",
    roles: [],
    permissions: [],
    userId: "",
    monitoringValue: '',
    gather: '',
  }),
  actions: {
    // socket 触发
    changeSocket () {
      this.socket++
    },
    /**
     *修改实时数据
     *  */

    getMonitoring (v) {
      this.monitoringValue = v
    },
    /**
     * 修改采集详情的数据
     */
    getGather (v) {
      this.gather = v

    },
    // 获取当前消息提醒数量
    async setMsgTotal () {
      const result = await GetNoMessageAPI()
      console.log("执行", result)
      this.msgTotal = Number(result)
    },

    setMsgIsShow (t) {
      this.msgIsShow = t
    },

    // 更新账套
    upZhangSet (zhangSet) {
      this.accountsId = zhangSet
    },
    // 登录
    login (userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      return new Promise((resolve, reject) => {
        login({ username, password })
          .then((res) => {
            setToken(res.data.access_token)
            this.token = res.data.access_token
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    //手机号登录
    iphoneLogin (userInfo) {
      const phoneNumber = userInfo.phoneNumber
      const smsCode = userInfo.smsCode
      return new Promise((resolve, reject) => {
        smsLoginAPI({ phoneNumber, smsCode })
          .then((res) => {
            setToken(res.data.access_token)
            this.token = res.data.access_token
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    //账套保存
    saveAccount (userInfo) {
      const phoneNumber = userInfo.phoneNumber
      const accountsName = userInfo.accountsName
      const accountsType = userInfo.accountsType
      const accountsTime = userInfo.accountsTime
      return new Promise((resolve, reject) => {
        saveAccountAPI({
          phoneNumber,
          accountsName,
          accountsType,
          accountsTime,
        })
          .then((res) => {
            setToken(res.data.access_token)
            this.token = res.data.access_token
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    getInfo () {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(({ data: res }) => {
            const user = res.user
            const avatar =
              user.avatar == "" || user.avatar == null ? defAva : user.avatar
            if (res.roles && res.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ["ROLE_DEFAULT"]
              this.roles = ["admin"]
              this.permissions = ["*:*:*"]
            }
            this.accountsId = user.accountsId
            this.username = user.userName
            this.userId = user.userId
            this.nickName = user.nickName
            this.avatar = avatar
            this.workbenchDataType = res.workbenchDataType
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 退出系统
    logOut () {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = ""
            this.roles = []
            this.permissions = []
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
  },
})

export default useUserStore
